'use strict';
const Path = require("path"), fs = require('fs');

module.exports = (request, response, rfun)=>{
    //读取本地文件
	let path = request.GET.pathname;
	path = Path.normalize(path).replace(/\.\./g, "");
	path = Path.normalize(path);
	path = request.SITE["root"] + path;
    fs.stat(path, onStat);
	
	function onStat(err, stats){
		if(err && err.code == 'ENOENT'){
			if(rfun) rfun();
			else if(request.SITE.proxy){
				let runMod = require("./proxy");
				runMod(request,response,rfun);
			}else{
                response.statusCode = 404;
				response.end("not find file");
            }
		}else{
			if(stats.isDirectory()){
				path += "/index.html";
				fs.stat(path, onStat);
			}else{
				if(Path.extname(path) == "") response.setHeader("Content-Type", "text/html; charset=utf-8");
				//判断是否是纯静态文件
				if(response.DATA){
					if(request.SITE["title"] && !response.DATA["title"]) response.DATA["title"] = request.SITE["title"];
					fs.readFile(path, (err, data) => {
						if(Buffer.isBuffer(data)) data = data.toString();
						for(var k in response.DATA){
							data = data.replace(new RegExp("\\{\\{"+k+"\\}\\}", 'g'), response.DATA[k]);
						}
						response.end(data);
						if(rfun) rfun();
					});
				}else{
					if(request.headers['if-modified-since'] == stats.mtime.toUTCString()){
						response.statusCode = 304;
						response.end();
					}else{
						response.setHeader("last-modified", stats.mtime.toUTCString());
						let stream = fs.createReadStream(path);
						stream.pipe(response);				
					}
					if(rfun) rfun();
				}
			}
		}
	}
}